package me.hl.guava.eventBus;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by haoliang on 2016/7/22.
 */
public class EventBusTest {

    private final Executor executor = Executors.newFixedThreadPool(5);

    //记得用异步的。。不然用同步的会夯住主线程的
    private final AsyncEventBus asyncEventBus = new AsyncEventBus("massage_sender", executor);

    private static Logger logger = LoggerFactory.getLogger(EventBusTest.class);


    //在spring容器中可以用@PostConstruct
    void init() {

        logger.info("init");
        asyncEventBus.register(new Object() {
            @Subscribe
            public void getMassage(MessageEvent event) {
                logger.info("event={}", event);
                //do something
            }
        });
    }

    public void sendMessage(MessageEvent messageEvent) {
        asyncEventBus.post(messageEvent);
    }

    static class MessageEvent {
        private final int id;
        private final String massage;

        public MessageEvent(int id, String massage) {
            this.id = id;
            this.massage = massage;
        }

        public int getId() {
            return id;
        }

        public String getMassage() {
            return massage;
        }

        @Override
        public String toString() {
            return "MessageEvent{" +
                    "id=" + id +
                    ", massage='" + massage + '\'' +
                    '}';
        }
    }

    public static void main(String args[]) {
        EventBusTest eventBusTest = new EventBusTest();
        eventBusTest.init();
        for (int i = 0; i < 10; i++) {
            MessageEvent messageEvent = new MessageEvent(i, "this is " + i + " message");
            logger.info("message send start");
            eventBusTest.sendMessage(messageEvent);
        }
        try {
            Thread.sleep(10000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

